package com.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        // 1. 创建线程池对象
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 2. 设置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(3);
        // 3. 设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(5);
        // 4. 设置队列容量
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 5. 设置线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 6. 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 7. 初始化线程池并返回
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
